package com.yyplatform.admin.platform.role.model.entity.converter;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yyplatform.admin.infra.exception.ErrorCode;
import com.yyplatform.admin.infra.exception.ServiceException;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import lombok.extern.slf4j.Slf4j;

/**
 * Created on 2024-09-18
 */
@Slf4j
@Converter
public class MenuParamConverter implements AttributeConverter<List<MenuParam>, String> {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public String convertToDatabaseColumn(List<MenuParam> attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            log.error("json转换错误", e);
            throw ServiceException.of(ErrorCode.UNKNOW_ERROR);
        }
    }


    @Override
    public List<MenuParam> convertToEntityAttribute(String dbData) {
        try {
            if (dbData == null) {
                return null;
            }
            return objectMapper.readValue(dbData, List.class);
        } catch (Exception e) {
            log.error("json转换错误", e);
            throw ServiceException.of(ErrorCode.UNKNOW_ERROR);
        }
    }
}
